<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #enable='{record}'>
            <a-tag v-if='record.enable' color='success'>{{$t('enable')}}</a-tag>
            <a-tag v-else>{{$t('disable')}}</a-tag>
        </template>
        <template #$action='{record}'>
            <BTextButton @click="resetPwd(record.id)">{{$t('resetPwd')}}</BTextButton>
        </template>
    </BPTable>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close='close'>
        <a-form :layout='i18n.locale == "ZH" ? "horizontal" : "vertical"' ref='formRef' :label-col='{span : i18n.locale == "ZH" ? 5 : 24}' :rules='rules' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item :label="$c('tenant', 'name')" name='name'>
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.name' />
            </a-form-item>
            <a-form-item v-if='!formData.id' :label='$t("account")' name='account'>
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.account' />
            </a-form-item>
            <a-form-item label='分成比例' name='profitRate'>
                <a-input :min="0" :max="100" type='number' v-model:value='formData.profitRate' suffix="%" />
            </a-form-item>
            <a-form-item :label='$t("role")' name='roles'>
                <a-select mode='multiple' v-model:value='formData.roles' :options='roleOptions' />
            </a-form-item>
            <a-form-item :label='$t("leader")' name='leader'>
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.leader' />
            </a-form-item>
            <a-form-item :label='$t("tel")' name='tel'>
                <a-input :maxlength='11' show-count type='text' v-model:value='formData.tel' />
            </a-form-item>
            <a-form-item :label='$t("enable")' name='enable'>
                <a-switch v-model:checked='formData.enable' :checked-children='i18n.t("enable")' :un-checked-children='i18n.t("disable")'/>
            </a-form-item>
        </a-form>
    </BDialog>
</template>

<script lang='ts' setup>
    import { nextTick, ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, pageApi, restpwdApi, saveApi } from "@/api/system/Tenant";
    import { listApi as roleListApi} from '@/api/system/Role'
    import { parseTime } from "@/utils";
import { useResourceStore } from "@/store/resource";
import { useI18nStore } from "@/store/i18n";

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const tableRef = ref()


    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission('system:tenant:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                getRoleList()
                dialogTitle.value = i18n.t('add')
                visible.value = true
            }
        })
    }



    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : i18n.t('name'),
            inSearch : true,
        },

        {
            dataIndex : 'admin',
            title : i18n.t('administrator'),
            customRender({text}) {
                return text ? text.name : ''
            },
        },

        {
            dataIndex : 'admin',
            title : i18n.t('account'),
            customRender({text}) {
                return text ? text.account : ''
            },
        },

        {
            dataIndex : 'profitRate',
            title : '费率',
            customRender({text}) {
                text = Number(text)
                return text ? text + '%' : 0 
            },
        },

        {
            dataIndex : 'leader',
            title : i18n.t('leader'),
        },

        {
            dataIndex : 'tel',
            title : i18n.t('tel'),
        },

        {
            dataIndex : 'enable',
            title : i18n.t('enable'),
        },

        {
            title : i18n.t('createTime'),
            dataIndex : 'createTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        {
            title : i18n.t('updateTime'),
            dataIndex : 'updateTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },
        
        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit : resourceStore.hasPermission('system:tenant:edit') ? (row) => {
                getRoleList()

                dialogTitle.value = i18n.t('edit')
                visible.value = true
                nextTick(() => {
                    for(let k in formData.value) {
                        if(k == 'roles') {
                            formData.value[k] = row.admin.roles
                        }else {
                            if(k in row) {
                                formData.value[k] = row[k]
                            }
                        }
                        
                        
                    }
                })
            } : undefined,

            // $delete : resourceStore.hasPermission('system:tenant:delete') ? async(row, index) => {
            //     const res = await deleteApi(row.id)
            //     if(res.success) {
            //         tableRef.value.reload()
            //         message.success(i18n.t('deleteSuccess'))
            //     }else {
            //         message.error(res.msg)
            //     }
            // } : undefined
            
        },
    ])

    const dataRows = ref<any[]>([])
    const roleOptions = ref<any[]>([])

    const formData = ref({
        id : 0,
        projectId : '',
        name : '',
        profitRate : '',
        account : '',
        roles : [],
        leader : '',
        tel : '',
        enable : true,
    })

    const rules = {
        name : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'name')
            }
        ],

        account : [
            {
                required : true,
                message : i18n.concat('please', 'input', 'account')
            }
        ],

        
    }

    //获取角色
    async function getRoleList() {
        if(roleOptions.value.length == 0) {
            roleListApi().then(res => {
                res.data.forEach(v => {
                    if(v.enable) {
                        roleOptions.value.push({value : v.id, label : v.name})
                    }
                })
            })
        }
        
    }

    //关闭的时候清空表单
    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()
    }

    

    async function submit() {
        let params  = await formRef.value.validate()
        params.status = Number(params.status)
        params.profitRate = Number(params.profitRate)
        
        const res = await saveApi(params)
        if(res.success) {
            tableRef.value.reload()
            message.success(i18n.t('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }

    function resetPwd(id:number) {
        Modal.confirm({
            content : i18n.concat('confirm', 'resetPwd', 'doubtSymbol'),
            async onOk() {
                const res = await restpwdApi(id)
                if(res.success) {
                    message.success(i18n.t('operateSuccess'))
                }else {
                    Modal.error({
                        title : res.msg
                    })
                }
            }
        })
    }


</script>